package com.example.mall_system.controller;

import com.example.mall_system.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Value("${file.upload.path:uploads/}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:/uploads/}")
    private String urlPrefix;

    @PostMapping("/image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        // 验证文件
        if (file.isEmpty()) {
            return Result.error(400, "请选择要上传的图片");
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.error(400, "只能上传图片文件");
        }

        // 验证文件大小 (2MB)
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.error(400, "图片大小不能超过2MB");
        }

        try {
            // 创建上传目录
            String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String fullUploadPath = uploadPath + datePath;
            Path uploadDir = Paths.get(fullUploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = uploadDir.resolve(filename);
            Files.copy(file.getInputStream(), filePath);

            // 返回文件URL
            String fileUrl = urlPrefix + datePath + "/" + filename;
            
            return Result.success(fileUrl);
            
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(500, "文件上传失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/image")
    public Result<String> deleteImage(@RequestParam("url") String imageUrl) {
        try {
            // 从URL中提取文件路径
            if (imageUrl.startsWith(urlPrefix)) {
                String relativePath = imageUrl.substring(urlPrefix.length());
                Path filePath = Paths.get(uploadPath, relativePath);
                
                if (Files.exists(filePath)) {
                    Files.delete(filePath);
                    return Result.success("图片删除成功");
                } else {
                    return Result.error(404, "文件不存在");
                }
            } else {
                return Result.error(400, "无效的文件URL");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(500, "文件删除失败: " + e.getMessage());
        }
    }
} 